//
//  GoodsDetailsViewController.m
//  Store
//
//  Created by Chuz NetTech on 17/4/10.
//  Copyright © 2017年 Chuz NetTech. All rights reserved.
//

#import "GoodsDetailsViewController.h"
#import "GoodsDetailsTableViewCell.h"
#import "BDUserModel.h"
#import "SDCycleScrollView.h"
#import "BDVipPayView.h"
#import "BDUserAddressModel.h"
#import "BDAddAddressViewController.h"
#import "AppDelegate.h"
#import "BDPayViewController.h"

/****     frame    ****/
#define kFCScreenWidth  ([UIScreen mainScreen ].bounds.size.width)
#define kFCScreenHeight ([UIScreen mainScreen ].bounds.size.height)

@interface GoodsDetailsViewController ()<UITableViewDelegate,UITableViewDataSource, UIWebViewDelegate, SDCycleScrollViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) BDButton *goumaiButton;
@property (nonatomic, strong) SDCycleScrollView *lunbo;

@end

@implementation GoodsDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = ASLocalizedString(@"商品详情");
    
    [self.view addSubview:self.goumaiButton];
    
    [self requestDatasource];
}

- (void)requestDatasource{
    NSString *url = [NSString stringWithFormat:@"%@product/%@", KBDBaseURL, @(self.detailsModel.product_id)];
    NSString *headValid = [BDUserModel getHeaderValidation];
    
    RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    
    [signal subscribeNext:^(id  _Nullable x) {
        self.detailsModel = [BDMallProductModel mj_objectWithKeyValues:x];
        NSInteger width = (kBDScreenWidth - 20);
        if ([self.detailsModel.content isNotEmpty]) {
            NSString *headString = [NSString stringWithFormat:@"<head><style>img{max-width:%@px !important;}</style></head>", @(width)];
            self.detailsModel.content = [headString stringByAppendingString:self.detailsModel.content];
        }else{
            self.detailsModel.content = ASLocalizedString(@"暂时还没有图片");
        }
        [self.tableView reloadData];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        // BDLog(ASLocalizedString(@"请求数据失败%@"), error);
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    GoodsDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL"];
    if (!cell) {
        cell = [[GoodsDetailsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CELL"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.section == 0) {
        NSDate *curDate = [NSDate dateWithTimeIntervalSince1970:self.detailsModel.validity];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        NSString *dateStr = [formatter stringFromDate:curDate];
        cell.textLabel.text = [NSString stringWithFormat:ASLocalizedString(@"有效期：至%@"), dateStr];
    }else{
        cell.textLabel.text = ASLocalizedString(@"详情说明：");
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 35;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 10;
    }else{
        return 0;
    }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    webView.height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
    webView.scrollView.scrollEnabled = NO;
    self.footerView.height = webView.bottom-20;
    [self.tableView reloadData];
}

- (SDCycleScrollView *)lunbo{
    if (!_lunbo) {
        self.lunbo = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kBDScreenWidth, 175 * kBDScreenWidth / 375) delegate:self placeholderImage:[UIImage imageNamed:@"shop_pic"]];
    }
    return _lunbo;
}

- (UIView *)headerView{
    if (!_headerView) {
        self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kFCScreenWidth, 0)];
        _headerView.backgroundColor = [UIColor whiteColor];
//        _headerView.backgroundColor = [UIColor clearColor];
        self.lunbo.imageURLStringsGroup = self.detailsModel.images;
        [_headerView addSubview:self.lunbo];
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.textColor = [UIColor colorWithHexString:@"101010"];
        titleLabel.text = self.detailsModel.title;
        titleLabel.font = [UIFont systemFontOfSize:17];
        titleLabel.numberOfLines = 0;
        titleLabel.width = kBDScreenWidth - 20;
        titleLabel.height = [titleLabel.text heightWithFont:titleLabel.font width:titleLabel.width];
        titleLabel.left = 10;
        titleLabel.top = self.lunbo.bottom + 15;
        [_headerView addSubview:titleLabel];
        
        UILabel *integralLabel = [[UILabel alloc] init];
        integralLabel.textColor = [UIColor colorWithHexString:@"ff6000"];
        integralLabel.text = [NSString stringWithFormat:ASLocalizedString(@"%@ 元"), @(self.detailsModel.money)];
//        integralLabel.attributedText = [self changePointStringColor];
        integralLabel.font = [UIFont systemFontOfSize:17];
        [integralLabel sizeToFit];
        integralLabel.left = 10;
        integralLabel.top = titleLabel.bottom + 10;
        [_headerView addSubview:integralLabel];
        
        UILabel *priceLabel = [[UILabel alloc] init];
        priceLabel.textColor = [UIColor colorWithHexString:@"cccccc"];
        priceLabel.font = [UIFont systemFontOfSize:13];
        
        NSString *priceStr = @"￥199.0";
        //中划线
        NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:priceStr attributes:attribtDic];
        // 赋值
        priceLabel.attributedText = attribtStr;
        [priceLabel sizeToFit];
        priceLabel.left = integralLabel.right + 12;
        priceLabel.bottom = integralLabel.bottom;
        [_headerView addSubview:priceLabel];
        priceLabel.hidden = YES;
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kFCScreenWidth, 1)];
        lineView.bottom = priceLabel.bottom + 10;
//        lineView.backgroundColor = [UIColor colorWithHexString:@"e5e5e5"];
        [_headerView addSubview:lineView];
        
        _headerView.height = lineView.bottom;
    }
    return _headerView;
}

- (UIView *)footerView{
    if (!_footerView) {
        self.footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0)];
        self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 500)];
        [self.webView loadHTMLString:self.detailsModel.content baseURL:nil];
        self.webView.delegate = self;
        [_footerView addSubview:self.webView];
        _footerView.height = self.webView.height-20;
        
        /*
         cell.careLabel.text = ASLocalizedString(@"注意事项");
         
         cell.distributionLabel.text = ASLocalizedString(@"1、配送区域：仅限中国大陆地区\n2、配送区域：仅限中国大陆地区\n3、配送区域：仅限中国大陆地区\n4、配送区域：仅限中国大陆地区\n");
         */
    }
    return _footerView;
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kFCScreenWidth, self.goumaiButton.top - 10 - kBDTopHeight) style:UITableViewStyleGrouped];
        _tableView.sectionFooterHeight = 0;
        _tableView.sectionHeaderHeight = 0;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.bounces = NO;
        _tableView.tableHeaderView = self.headerView;
        _tableView.tableFooterView = self.footerView;
        [_tableView registerClass:[GoodsDetailsTableViewCell class] forCellReuseIdentifier:@"CELL"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (UIButton *)goumaiButton{
    if (!_goumaiButton) {
        self.goumaiButton = [BDButton buttonWithType:UIButtonTypeCustom];
        _goumaiButton.size = CGSizeMake(kBDScreenWidth - 20, 47);
        _goumaiButton.bottom = kBDScreenHeight - 10;
        _goumaiButton.centerX = kBDScreenWidth / 2.0;
        [_goumaiButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_goumaiButton setTitle:ASLocalizedString(@"购买")forState:UIControlStateNormal];
        _goumaiButton.titleLabel.font = [UIFont systemFontOfSize:18];
        _goumaiButton.layer.cornerRadius = 5;
        _goumaiButton.backgroundColor = [UIColor colorWithHexString:@"4d7aad"];
        __weak GoodsDetailsViewController *weakSelf = self;
        
        [[_goumaiButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [BDUserModel judgeCurrentUserWithNormalBlock:^{
                BDPayViewController *payVC = [[BDPayViewController alloc] init];
                payVC.product = self.detailsModel;
                payVC.payType = BDProductPayTypeProduct;
                payVC.productId = [NSString stringWithFormat:@"%@", @(self.detailsModel.product_id)];
                payVC.price = [NSDecimalNumber decimalNumberWithDecimal:[@(self.detailsModel.money) decimalValue]];
                [weakSelf.navigationController pushViewController:payVC animated:YES];
            }];
        }];
    }
    return _goumaiButton;
}

- (void)startPayWithAddressArray:(NSArray *)addressArray{
    BDVipPayView *payView = [BDVipPayView showWithProductId:self.detailsModel.product_id type:BDPayTypeProduct title:ASLocalizedString(@"购买商品")product:self.detailsModel.title price:[NSString stringWithFormat:ASLocalizedString(@"%@ 元"), @(self.detailsModel.money)] addressArray:addressArray];
    
    __weak AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    app.payResultBlock = ^(int state) {
        app.payResultBlock = nil;
        [payView hidden];
        if (state == 1) {
            [MBManager showBriefAlert:ASLocalizedString(@"购买成功")clickHidden:YES clickBlock:nil];
        }else if (state == 2) {
            [MBManager showBriefAlert:ASLocalizedString(@"支付失败")clickHidden:YES clickBlock:nil];
        }else if (state == 3) {
            [MBManager showBriefAlert:ASLocalizedString(@"支付取消")clickHidden:YES clickBlock:nil];
        }
    };
}

-(NSMutableAttributedString *)changePointStringColor{
    NSString *str = [NSString stringWithFormat:ASLocalizedString(@"%@元"),@"299"];
    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:str attributes:nil];
    NSRange range = [str rangeOfString:@"299"];
    NSRange secondRange = [str rangeOfString:ASLocalizedString(@"元")];
    [attribute addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    [attribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:22] range:range];
    [attribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:secondRange];
    return attribute;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
